package models
type SystemLevel struct {
	Id          int       `json:"id" xorm:"not null pk autoincr comment('主键') INT(11)"`
	Parentid         int       `json:"parentId" xorm:"not null  comment('父阶段id') INT(11)"`
	Level        int       `json:"level" xorm:"not null  comment('在阶段树里的层级') INT(11)"`
	Name        string    `json:"name" xorm:"not null comment('阶段名称') VARCHAR(100)"`

}
var systemlevel = "system_level"


func(l *SystemLevel) GetRow() bool {
	has, err := mEngine.Get(l)
	if err==nil &&  has  {
		return true
	}
	return false
}
func  (l *SystemLevel) GetAll() ([]SystemLevel,error) {

	var systemlevels []SystemLevel
	err:=mEngine.Find(&systemlevels)
	return systemlevels,err
}
func (l *SystemLevel) Add() error{
	session := mEngine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		// if returned then will rodefer session.Close()llback automatically
		return err
	}
	//var uid int64
	_,err:=session.Insert(l)
	if err!=nil {
		return err
	}

	return session.Commit()
}
func (l *SystemLevel) Update() error{
	session := mEngine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		// if returned then will rodefer session.Close()llback automatically
		return err
	}

	_, err :=mEngine.Where("id = ?", l.Id).Update(l)

	if err!=nil {
		return err
	}

	return session.Commit()
}
func (l *SystemLevel) Delete() error {
	//如果删除，将彻底删除子阶段以及所有相关的试题，知识点和题目来源
	session := mEngine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		// if returned then will rodefer session.Close()llback automatically
		return err
	}
	var id=l.Id

	//删除自身阶段

	_,err:=mEngine.Exec("delete from "+systemlevel + " where id=?",id)
	//delete from system_type where not exists (select 1 from system_subject_type where system_subject_type.type_id =system_type.id )
	//删除来源信息,如果这个来源不关联到任何阶段
	if _, err :=mEngine.Exec("delete from "+systemsource+" where not exists (select 1 from "+systemsourcelevel+" where "+systemsourcelevel+".source_id ="+systemsource+".id )"); err != nil {
		return err

	}


	//删除知识点信息,如果这个知识点不关联到任何阶段
	if _, err :=mEngine.Exec("delete from "+systemknowledge+" where not exists (select 1 from "+systemknowledgelevel+" where "+systemknowledgelevel+".knowledge_id ="+systemknowledge+".id )"); err != nil {
		return err

	}
	//删除试题信息,如果这个试题不关联到任何阶段
	if _, err :=mEngine.Exec("delete from "+systemquestion+" where not exists (select 1 from "+systemquestionlevel+" where "+systemquestionlevel+".question_id ="+systemquestion+".id )"); err != nil {
		return err

	}

	//删除孤立的试卷
	if _, err :=mEngine.Exec("delete from "+userexam+" where not exists (select 1 from "+userexamquestion+" where "+userexamquestion+".exam_id ="+userexam+".id )"); err != nil {
		return err

	}
	if err!=nil{
		return err
	}
	return session.Commit()
}